package com.tek.ding.faceding.network.rx;


import com.tek.ding.faceding.bean.BaseBean;
import com.tek.ding.faceding.network.exception.ApiException;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.core.ObservableTransformer;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class RxHttpResponseCompat {

    public static <T> ObservableTransformer<BaseBean<T>, BaseBean<T>> compatResult() {

        return new ObservableTransformer<BaseBean<T>, BaseBean<T>>() {

            @Override
            public @NonNull Observable<BaseBean<T>> apply(@NonNull Observable<BaseBean<T>> baseBeanObservable) {

                return baseBeanObservable.flatMap(new Function<BaseBean<T>, ObservableSource<BaseBean<T>>>() {
                    @Override
                    public ObservableSource<BaseBean<T>> apply(BaseBean<T> tBaseBean) throws Throwable {
                        if (tBaseBean.error()) {
                            return Observable.error(new ApiException(tBaseBean.getSt(), tBaseBean.getMsg()));
                        } else {
                            return Observable.create(new ObservableOnSubscribe<BaseBean<T>>() {
                                @Override
                                public void subscribe(@NonNull ObservableEmitter<BaseBean<T>> observableEmitter) throws Throwable {
                                    try {
                                        observableEmitter.onNext(tBaseBean);
                                        observableEmitter.onComplete();
                                    } catch (Exception e) {
                                        observableEmitter.onError(e);
                                    }
                                }
                            });
                        }
                    }
                })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

}
